package com.ebt.m.customer.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ebt.m.R;
import com.ebt.m.commons.utils.NetUtils;
import com.ebt.m.customer.CustomerUtil;
import com.ebt.m.customer.constant.CustomerConstant;
import com.ebt.m.customer.event.EventCustomerMainContentViewDetach;
import com.ebt.m.customer.event.EventMultiChooseAll;
import com.ebt.m.customer.event.EventMultiChooseOff;
import com.ebt.m.customer.event.EventMultiChooseOn;
import com.ebt.m.customer.event.EventMultiChooseUpdateCount;
import com.ebt.m.customer.event.EventMultiUnchooseAll;
import com.ebt.m.customer.interfaces.IMultiChoose;
import com.ebt.m.customer.model.CustomerModelNew;
import com.ebt.m.customer.ui.ActivityCustomerAll;
import com.ebt.m.customer.util.MultiChooseManager;
import com.jakewharton.rxbinding2.view.RxView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

/**
 * Created by Rick.Wang on 2016/4/12.
 */
public class CustomerItemMainNormal extends FrameLayout implements ICustomizedViewNew, View.OnLongClickListener, IMultiChoose {

    private View mItemView;
    private TextView mTitleView;
    private TextView mNameView;
    private ImageView mTagImageView;
    private ImageView mSquareAvatarView;
    private CustomerModelNew mCustomerModelNew;
    private Context mContext;
    private CheckBox mMultiCheckBox;

    public CustomerItemMainNormal(Context context) {
        this(context, null);
    }

    public CustomerItemMainNormal(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CustomerItemMainNormal(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        View contentView = inflate(context, R.layout.view_customer_item_main, this);
        mItemView = contentView.findViewById(R.id.rl_item_view);
        mTagImageView = (ImageView) contentView.findViewById(R.id.iv_tag);
        mTitleView = (TextView) contentView.findViewById(R.id.tv_title);
        mSquareAvatarView = (ImageView) contentView.findViewById(R.id.iv_avatar);
        mNameView = (TextView) contentView.findViewById(R.id.tv_name);
        mMultiCheckBox = (CheckBox) contentView.findViewById(R.id.iv_select);
        mItemView.setOnLongClickListener(this);
        RxView.clicks(mMultiCheckBox)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    clicked();
                });
        RxView.clicks(mItemView)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(aVoid -> {
                    clicked();
                });
    }

    private void clicked() {
        //没有处在删除状态时，跳转到删除状态，并删除某一个客户
        if (getInMultiChooseMode()) {
            selectOrUnselect(mCustomerModelNew.getCustomerUuid());
            return;
        }
        if (NetUtils.isNetworkAvailable(getContext().getApplicationContext())) {
            Intent intent = new Intent(mContext, ActivityCustomerAll.class);
            intent.putExtra(CustomerConstant.CUSTOMER_DETAIL_MODE, CustomerConstant.CUSTOMER_DETAIL_MODE_EDIT);
            intent.putExtra(CustomerConstant.CUSTOMER_UUID, mCustomerModelNew.getCustomerUuid());
            intent.putExtra(CustomerConstant.CustomerAll.VIEW_PAGER_INDEX, CustomerConstant.CustomerAll.VIEW_PAGER_INDEX_PROFILE);
            intent.putExtra(CustomerConstant.CUSTOMER_DATA, mCustomerModelNew);
            intent.putExtra(CustomerConstant.SpreadAnim.URL_AVATAR, mCustomerModelNew.avatarUrl);
            intent.putExtra(CustomerConstant.SpreadAnim.SEX, mCustomerModelNew.sex == null ? 0 : mCustomerModelNew.sex);
            ActivityCompat.startActivity(getContext(), intent, ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) getContext(), mSquareAvatarView, "translate_view").toBundle());
        } else {
            Toast.makeText(getContext().getApplicationContext(), getContext().getString(R.string.network_fail), Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
//        EventBus.getDefault().unregister(this);
    }


    @Override
    public boolean onLongClick(View view) {
        switch (view.getId()) {
            case R.id.rl_item_view:
                if (!getInMultiChooseMode()) {//没有处在删除状态时，跳转到删除状态，并删除某一个客户
                    toMultiChooseMode();
                    select((String) view.getTag());
                } else {//处于删除状态时，
                    selectOrUnselect((String) view.getTag());
                }
                return true;
        }
        return false;
    }

    private void selectOrUnselect(String uuid) {
        if (getSelected(uuid)) {
            unselect(uuid);
        } else {
            select(uuid);
        }
    }

    @Override
    public View getView() {
        return this;
    }

    @Override
    public void update(CustomerModelNew model) {
        mCustomerModelNew = model;
        if (model == null) {
            return;
        }
        mNameView.setText(model.name);
        if (model.tag == null || model.tag == 0) {
            mTagImageView.setVisibility(View.INVISIBLE);
        } else {
            mTagImageView.setVisibility(View.VISIBLE);
        }
        CustomerUtil.setAvatarByUrlAndSex(getContext(), mSquareAvatarView, model.avatarUrl, model.sex);
        mItemView.setTag(model.getCustomerUuid());
        //更新多选状态
        updateCheckbox(model.getCustomerUuid());
    }

    private void updateCheckbox(String uuid) {
        if (getInMultiChooseMode()) {
            mMultiCheckBox.setChecked(getSelected(uuid));
            mMultiCheckBox.setVisibility(View.VISIBLE);
        } else {
            mMultiCheckBox.setChecked(false);
            mMultiCheckBox.setVisibility(View.GONE);
        }
    }

    @Override
    public void showSortTitle(String sortTitle) {
        if (TextUtils.isEmpty(sortTitle)) {
            mTitleView.setVisibility(View.GONE);
        } else {
            mTitleView.setVisibility(View.VISIBLE);
            mTitleView.setText(sortTitle);
        }
    }

    //多选相关的回调函数
    @Override
    public void unselect(String uuid) {
        MultiChooseManager.getInstance().setFlag(uuid, false);
        mMultiCheckBox.setChecked(false);
        EventBus.getDefault().post(new EventMultiChooseUpdateCount());
    }

    @Override
    public void select(String uuid) {
        MultiChooseManager.getInstance().setFlag(uuid, true);
        mMultiCheckBox.setChecked(true);
        EventBus.getDefault().post(new EventMultiChooseUpdateCount());
    }

    @Override
    public void toMultiChooseMode() {
        MultiChooseManager.getInstance().setInMultiChooseMode(true);
        MultiChooseManager.getInstance().clearFlags();
        EventBus.getDefault().post(new EventMultiChooseOn());
    }

    @Override
    public void toNormalMode() {
        MultiChooseManager.getInstance().setInMultiChooseMode(false);
        MultiChooseManager.getInstance().clearFlags();
        mMultiCheckBox.setChecked(false);
        mMultiCheckBox.setVisibility(View.GONE);
    }

    @Override
    public boolean getInMultiChooseMode() {
        return MultiChooseManager.getInstance().getInMultiChooseMode();
    }

    @Override
    public boolean getSelected(Object o) {
        return MultiChooseManager.getInstance().getFlag(o);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseOff event) {
        toNormalMode();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventCustomerMainContentViewDetach event) {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseOn event) {
        mMultiCheckBox.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiChooseAll event) {
        mMultiCheckBox.setChecked(true);
        mMultiCheckBox.setVisibility(View.VISIBLE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(EventMultiUnchooseAll event) {
        mMultiCheckBox.setChecked(false);
//        mMultiCheckBox.setVisibility(View.VISIBLE);
    }

}